package com.example.photograph.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.photograph.domain.AppPhoneDataVo;
import com.example.photograph.domain.LoginData;
import com.example.photograph.domain.ResutltAndCookie;
import com.example.photograph.domain.SysAppPhone;
import com.example.photograph.mapper.SysAppPhoneMapper;
import com.example.photograph.service.ISysAppPhoneService;
import com.example.photograph.utils.Convert;
import com.example.photograph.utils.HttpUtil;
import com.example.photograph.utils.HutoolUtil;
import com.example.photograph.utils.ShiroUtils;
import org.json.Cookie;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @author panhm
 * @date 2022-07-07
 * @Description:
 */
@Service("SysAppPhoneServiceImpl")
public class SysAppPhoneServiceImpl implements ISysAppPhoneService {
    @Resource
    private SysAppPhoneMapper sysAppPhoneMapper;

    /**
     * 查询套餐管理
     *
     * @param id 套餐管理ID
     * @return 套餐管理
     */
    @Override
    public SysAppPhone selectSysAppPhoneById(Long id) {
        return sysAppPhoneMapper.selectSysAppPhoneById(id);
    }

    /**
     * 查询套餐管理列表
     *
     * @param sysAppPhone 套餐管理
     * @return 套餐管理
     */
    @Override
    public List<AppPhoneDataVo> selectSysAppPhoneList(SysAppPhone sysAppPhone) {

        List<SysAppPhone> sysAppPhones = sysAppPhoneMapper.selectSysAppPhoneList(sysAppPhone);
        if (CollectionUtils.isEmpty(sysAppPhones)){
            return new ArrayList<>();
        }



        return sysAppPhones.stream().map(this::toAppPhoneDataVo).collect(Collectors.toList());
    }


    @Override
    public List<SysAppPhone> selectSysAppPhoneListV1(SysAppPhone sysAppPhone) {

        List<SysAppPhone> sysAppPhones = sysAppPhoneMapper.selectSysAppPhoneList(sysAppPhone);
        if (CollectionUtils.isEmpty(sysAppPhones)){
            return new ArrayList<>();
        }



        return sysAppPhones;
    }
    private AppPhoneDataVo toAppPhoneDataVo(SysAppPhone data) {
        AppPhoneDataVo appPhoneDataVo = new AppPhoneDataVo();
        appPhoneDataVo.setPhone(data.getPhone());
        long expectedTime = data.getLastUpdateTime() + 7200000L;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        appPhoneDataVo.setExpectedTime(simpleDateFormat.format(new Date(expectedTime)));
        boolean expire = System.currentTimeMillis() > expectedTime;
        appPhoneDataVo.setIsExPire(expire ? "是" : "否");
        appPhoneDataVo.setCookie(data.getCookie());
        appPhoneDataVo.setId(data.getId());
        return appPhoneDataVo;
    }
    /**
     * 新增套餐管理
     *
     * @param sysAppPhone 套餐管理
     * @return 结果
     */
    @Override
    public int insertSysAppPhone(SysAppPhone sysAppPhone) {
        // SysAppPhone.setCreateTime(DateUtils.getNowDate());
        return sysAppPhoneMapper.insertSysAppPhone(sysAppPhone);
    }

    /**
     * 修改套餐管理
     *
     * @param sysAppPhone 套餐管理
     * @return 结果
     */
    @Override
    public int updateSysAppPhone(SysAppPhone sysAppPhone) {
        return sysAppPhoneMapper.updateSysAppPhone(sysAppPhone);
    }

    /**
     * 删除套餐管理对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysAppPhoneByIds(String ids) {
        return sysAppPhoneMapper.deleteSysAppPhoneByIds(Convert.toLongArray(ids));
    }

    /**
     * 删除套餐管理信息
     *
     * @param id 套餐管理ID
     * @return 结果
     */
    @Override
    public int deleteSysAppPhoneById(Long id) {
        return sysAppPhoneMapper.deleteSysAppPhoneById(id);
    }

    @Override
    public String getCookie(Long id) {
        SysAppPhone sysAppPhone = this.selectSysAppPhoneById(id);
        if (sysAppPhone==null){
            return "cookie不存在!";
        }
        String cookie ="";
        JSONObject jsonObject = Cookie.toJSONObject(sysAppPhone.getCookie());
        try {
            Object value = jsonObject.get("remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d");

            cookie = "remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d="+"="+value.toString();

        }catch (JSONException e){
            Object name = jsonObject.get("name");
            Object value = jsonObject.get("value");
            cookie =name.toString()+"="+value.toString();
        }
        cookie = HttpUtil.refreshCookie(cookie);
        return cookie == null ? "账号已过期!" : "document.cookie='" + cookie + "'";
    }

    @Override
    public String sendSms(String phone) {
        try {
            String result = HttpUtil.sendPost("https://wap.fj.10086.cn/store/api/sms/verification/fetch", Collections.singletonMap("mobile", phone));
            Object message = JSON.parseObject(result).get("message");
            return message != null ? message.toString() : "发送短信失败!" + unicode2String(result);
        } catch (Exception var4) {
            return var4.getMessage();
        }
    }

    @Override
    public String login(LoginData loginData) {
        ResutltAndCookie login = HutoolUtil.login(loginData.getPhone(), loginData.getCode());
        if (this.isSussess(login.getResult())) {
            SysAppPhone appPhoneData = new SysAppPhone();
            appPhoneData.setPhone(loginData.getPhone());
            appPhoneData.setCookie(login.getCookie());
            appPhoneData.setLastUpdateTime(System.currentTimeMillis());
            appPhoneData.setUserId(ShiroUtils.getUserId());
            this.insertSysAppPhone(appPhoneData);
            return "登录成功!";
        } else {
            return "登录失败!" + login.getResult();
        }
    }
    private boolean isSussess(String resut) {
        if (resut == null) {
            return false;
        } else {
            try {
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(resut);
                return jsonObject.get("message") != null && jsonObject.get("message").equals("登陆成功");
            } catch (Exception var3) {
                return false;
            }
        }
    }
    private static   String unicode2String(String unicode) {
        if (org.apache.commons.lang3.StringUtils.isBlank(unicode)) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        int i = -1;
        int pos = 0;

        while ((i = unicode.indexOf("\\u", pos)) != -1) {
            sb.append(unicode.substring(pos, i));
            if (i + 5 < unicode.length()) {
                pos = i + 6;
                sb.append((char) Integer.parseInt(unicode.substring(i + 2, i + 6), 16));
            }
        }
        //如果pos位置后，有非中文字符，直接添加
        sb.append(unicode.substring(pos));

        return sb.toString();
    }
}